﻿using MES.Server.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace MES.Server.Utility.Filters
{
    /// <summary>
    /// 异常处理
    /// </summary>
    public class CustomAsyncExceptionFilterAttribute : Attribute, IAsyncExceptionFilter
    {
        private ILogger<CustomAsyncExceptionFilterAttribute> _ILogger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name=""></param>
        public CustomAsyncExceptionFilterAttribute(ILogger<CustomAsyncExceptionFilterAttribute> logger)
        {
            _ILogger = logger;
        }


        /// <summary>
        /// 用作处理异常的
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                ////如果并发特别高，可以考虑吧消息写入到队列 或者是Redis，另外从队列中消费出来，写入到数据库中去了 
               
                _ILogger.LogError($"发生了异常，消息：{context.Exception.Message}");
                
                ///如果发生了异常，要记录日志
                ///log4net

                context.Result = new JsonResult(new ApiDataResult<string> { Success = false, Message = context.Exception.Message });
            }
            context.ExceptionHandled = true;
            await Task.CompletedTask;
        }
    }
}
